import { _decorator, Component, Enum, instantiate, Layout, Node, Prefab, tween, v3 } from 'cc';
import { ImageSpine } from './ImageSpine';
import { ImageSprite } from './ImageSprite';
import { Direction } from './SlotEnum';
const { ccclass, property } = _decorator;
/// 图片偏移的位置= 图片高度+间距 120+12
const pictureOffet = 132;
///动画时间
const animationTime = 0.05;
@ccclass('SpineClomn')
export class SpineClomn extends Component {
    /// 每列的滚轴的父节点的Layout
    @property({ type: Node })
    public clomnGroup: Node = null;
    /// 装每个spine的数组
    @property({ type: [Node], visible: false })
    private spinesArray: Node[] = [];
    /// 单张spine复用的预制体
    @property({ type: Prefab })
    public singalSpine: Prefab = null;

    ///滚动的方向
    @property({ type: Enum(Direction), tooltip: '滚动选择的方向' })
    public spinDirection: Direction = Direction.Down;

    private result: number[] = [];
    public stopSpinning: boolean = false;

    ///初始化
    protected onLoad(): void {
        this.clomnGroup.destroyAllChildren();
        this.spinesArray = [];
        ///如果复用的图片不为空则创建滚轴
        if (this.singalSpine != null) {
            this.createReel();
            this.shuffle();
        }
    }

    /** 创建滚轴2 */
    createReel(): void {
        console.log('建立滚轴,初始化5张图片');
        for (let i = 0; i < 5; i++) {
            const newImage = instantiate(this.singalSpine);
            this.clomnGroup.addChild(newImage);
            this.spinesArray[i] = newImage;
        }
        // 检查 Widget 组件是否存在
        const widgetComponent = this.clomnGroup.getComponent(Layout);
        if (widgetComponent) {
            widgetComponent.updateLayout();
        } else {
            console.error("Rool-Widget 组件未找到，请确保它已附加到节点上。");
        }
    }

    start() {

    }

    update(deltaTime: number) {

    }

    /** 重新设定图片和打乱图片 */
    shuffle(): void {
        console.log('打乱图片');
        this.spinesArray.forEach(tile => {
            tile.getComponent(ImageSpine).setRandom();
        });
    }

    /** 停止滚动 */
    readyStop(newResult: number[]): void {
        console.log('停止滚动');
        const check = this.spinDirection === Direction.Down || newResult == null;
        this.result = check ? newResult : newResult.reverse();
        this.stopSpinning = true;
    }

    /** 执行滚动的动画 */
    doSpinning(element: Node, times = 1,index:number): void {
        const dirModifier = this.spinDirection == Direction.Down ? -1 : 1;
         // 添加一个对属性进行 相对值 计算的间隔动作
        const move = tween(element).by(animationTime, { position: v3(0, pictureOffet * dirModifier) });
        //添加一个 调用回调 的瞬时动作
        const doChange = tween().call(() => this.changeDiceCallback(element,index));
        // 重复执行几次
        const repeat = tween(element).repeat(times, move.then(doChange));
        /// 检查是否需要结束动画 
        const checkEnd = tween().call(() => this.checkEndSpinCallback(element,index));
        ///重复5次后检查是否完成
        repeat.then(checkEnd).start();
    }

    /** 更换缓动动画的回调方法 */
    changeDiceCallback(element: Node,index:number): void {
        const dirModifier = this.spinDirection === Direction.Down ? -1 : 1;
        if (element.position.y * dirModifier > pictureOffet) {
            element.position = v3(0, -pictureOffet * dirModifier);
            console.log('取出结果数组的为空进行随机');
            const diceComponent = element.getComponent(ImageSpine);
            diceComponent.setRandom();
        }
    }

    /** 停止滚动动画的最后的操作 */
    checkEndSpinCallback(element: Node,index:number): void {
        if (this.stopSpinning) {
            this.doStop(element,index);
        } else {
            this.doSpinning(element,1,index);
        }
    }

    /** 开始执行添加缓动的动画 */
    doSpin(windUp: number): void {
        this.stopSpinning = false;
        for (let i = 0; i < this.clomnGroup.children.length; i++) {
            const eachNode = this.clomnGroup.children[i];
            const dirModifier = this.spinDirection === Direction.Down ? -1 : 1;
            tween(eachNode)
                .delay(windUp)
                .by(0.45, { position: v3(0, pictureOffet * dirModifier) }, { easing: 'backIn' })
                .call(() => this.changeDiceCallback(eachNode,i))
                .call(() => this.doSpinning(eachNode, 1,i))
                .start();
        }
    
    }

     /** 更换缓动动画的回调方法 */
     endChangeDiceCallback(element: Node,index:number): void {
        const dirModifier = this.spinDirection === Direction.Down ? -1 : 1;
    
        if (element.position.y * dirModifier > pictureOffet ) {
            element.position = v3(0, -pictureOffet * dirModifier);
            const diceComponent = element.getComponent(ImageSpine); 
            console.log('结果此时');
            let pop = null;
            if (this.result != null && this.result.length > 0) {
                // 从 result 中对应的数字
                pop = this.result[index];
            }
            console.log('得到的数字',pop);
            diceComponent.setDice(pop);
        }
    }

    /** 动画结束 */
    doStop(element: Node = null,index:number): void {
        //反向
        const dirModifier = this.spinDirection === Direction.Down ? -1 : 1;
       // 添加一个对属性进行 相对值 计算的间隔动作
        const move = tween(element).by(animationTime, { position: v3(0, pictureOffet * dirModifier) });
         //添加一个 调用回调 的瞬时动作 //添加一个 调用回调 的瞬时动作
        const doChange = tween().call(() => this.endChangeDiceCallback(element,index));

        const end = tween(element).by(0.45, { position: v3(0, pictureOffet * dirModifier) }, { easing: 'bounceOut' });
        ///执行3次doChange，得到移动元素到某个位置
        move
            .then(doChange)
            .then(move)
            .then(doChange)
            .then(end)
            .then(doChange)
            .start();
    }

}

